﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
using System.Drawing;

namespace LowLevelGraphics.ImageFormats
{
    /// <summary>
    /// PGM
    /// </summary>
    public class PGM : AbstractImageFormat, IImageFormat
    {
        /// <summary>
        /// returns Extension
        /// </summary>
        public override string Extension
        {
            get { return "pgm"; }
        }

        /// <summary>
        /// Creates the specified _s file name.
        /// </summary>
        /// <param name="_sFileName">Name of the _s file.</param>
        /// <returns></returns>
        public static UnsafeBitmap Create(string _sFileName)
        {
            StreamReader reader = new StreamReader(_sFileName);
            string sText = reader.ReadToEnd();
            string[] aLine = Regex.Split(sText, "\n|\t|\v\f\r ");
            string sSubFormat = aLine[0];
            string sWidthHeight = aLine[1];

            string[] aWidthHeight = aLine[1].Split(' ');
            int nWidth = Convert.ToInt32(aWidthHeight[0]);
            int nHeight = Convert.ToInt32(aWidthHeight[1]);
            string sMaxGrayValue = aLine[2];
            int nByte = Convert.ToInt32(sMaxGrayValue) < 256 ? 1 : 2;
            UnsafeBitmap bitmap = new Bitmap(nWidth, nHeight);

            int x = 0;
            int y = 0;

            int nOffset = aLine[0].Length + aLine[1].Length + aLine[2].Length;
            foreach (char ch in sText.Substring(nOffset, sText.Length - nOffset))
            {
                byte nValue = (byte)ch;
                bitmap.SetPixel(x, y, Color.FromArgb(nValue, nValue, nValue));
                x++;
                if (x > 512 - 1) { x = 0; y++; }
                if (y > 512 - 1) { break; }
            }
            return bitmap;
        }

        /// <summary>
        /// Save
        /// </summary>
        /// <param name="_sFileName"></param>
        /// <returns></returns>
        public override bool Save(string _sFileName)
        {
            throw new NotImplementedException();
        }
    }
}
